package dao

import (
	"context"
	"lion-passport/config"
	"lion-passport/internal/dao/query"
	"lion-passport/internal/utils/log"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var (
	_db *gorm.DB
)

func InitMySql() {
	dsn := config.GetEnv("MYSQL_DSN", "root:123456@tcp(127.0.0.1:3307)/db_lion_001?charset=utf8mb4&parseTime=True&loc=Local")
	var err error
	var ormLogger logger.Interface
	if gin.Mode() == gin.DebugMode {
		ormLogger = logger.Default.LogMode(logger.Info)
	} else {
		ormLogger = logger.Default.LogMode(logger.Silent)
	}
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: ormLogger,
	})
	if err != nil {
		log.LogrusObj.Error("数据库连接失败:", err)
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(20)  // 设置连接池，空闲
	sqlDB.SetMaxOpenConns(100) // 打开
	sqlDB.SetConnMaxLifetime(time.Second * 30)
	_db = db
	log.LogrusObj.Infoln("✅ 数据库连接成功")
	query.SetDefault(db)
}

func NewDBClient(ctx context.Context) *gorm.DB {
	db := _db
	return db.WithContext(ctx)
}
